package concurrency;


import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by sunzhengjie on 2017/1/17.
 */
public class TestShareData {

    public static abstract class IntGenerator {
        private volatile boolean canceled = false;

        public abstract int next();

        public void cancel() {
            canceled = true;
        }

        public boolean isCanceled() {
            return canceled;
        }
    }

    public static class EvenChecker implements Runnable {
        private IntGenerator generator;
        private final int id;

        public EvenChecker(int id, IntGenerator generator) {
            this.id = id;
            this.generator = generator;
        }

        @Override
        public void run() {
            while (!generator.isCanceled()) {
                int val = generator.next();
                if (val % 2 != 0) {
                    System.out.println(val + " not even!");
                    generator.cancel();
                }
            }
        }
    }

    public static void test(IntGenerator generator, int count) {
        System.out.println("Press Control-C to exit");
        ExecutorService exec = Executors.newCachedThreadPool();
        for (int i = 0; i < count; i++) {
            exec.execute(new EvenChecker(i, generator));
        }
        exec.shutdown();
    }

    public static void main(String[] arg0) throws IOException {
        test(new IntGenerator() {
            private volatile int currentEvenValue = 0;
            private Lock lock = new ReentrantLock();
            @Override
            public int next() {
                lock.lock();
                try{
                    ++currentEvenValue;//danger point here!
                    Thread.yield();
                    ++currentEvenValue;
                    return currentEvenValue;
                }finally {
                    lock.unlock();
                }
            }
        }, 1000);
    }
}
